package cn.tedu._05mvcboot02.controller;

import cn.tedu._05mvcboot02.common.response.JsonResult;
import cn.tedu._05mvcboot02.mapper.UserMapper;
import cn.tedu._05mvcboot02.pojo.dto.AddUserDTO;
import cn.tedu._05mvcboot02.pojo.entity.User;
import cn.tedu._05mvcboot02.pojo.vo.UserListVO1;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
@Api(tags="用户界面")
@Slf4j
@RestController
@RequestMapping(value = "/v1/users/")
public class UserController {
    //自动装配
    @Autowired
    private UserMapper userMapper;

    /**
     * 1.添加用户功能
     */
    @ApiOperation(value = "01.添加用户")
    @PostMapping(value = "insert")
    public JsonResult addUser(AddUserDTO addUserDTO){
        /*
            梳理业务逻辑,确定接口,以注册功能为例:
            1.接收客户端传递过来的数据;
            2.校验数据的合法性;
            3.确认用户名是否被占用[SELECT接口];
              3.1 被占用,return返回结束;
              3.2 未被占用,插入数据[INSERT接口];
              3.3 返回响应.
         */

        User user = new User();
        //复制属性
        BeanUtils.copyProperties(addUserDTO, user);
        user.setCreated(new Date());
        log.debug("user:"+user);
        userMapper.insertUser(user);

        return JsonResult.ok();
    }
    @ApiOperation(value = "02.查询用户")
    @GetMapping(value ="userList" )
    public JsonResult userList(){
        List<UserListVO1> userListVO1=userMapper.selectUserList();
        return JsonResult.ok(userListVO1);
    }
    @ApiImplicitParam(name="id",value = "用户ID",required = true,paramType = "int")
    @ApiOperation(value = "03.删除用户")
    @GetMapping(value ="delete" )
    public JsonResult deleteUser(int id){
        if(id<0){
            throw new IllegalArgumentException("ID值不能小于0");
        }
        log.debug("id:"+id);
        userMapper.deleteUser(id);
        return JsonResult.ok();
    }
    @ApiOperation(value = "04.修改用户")
    @PostMapping(value ="update" )
    public JsonResult updateUser(User user){
        log.debug("user:"+user);
        userMapper.updateUser(user);
        return JsonResult.ok();
    }
    @ApiImplicitParam(name="id",value = "用户ID",required = true,paramType = "int")
    @ApiOperation(value = "05.查询ID")
    @GetMapping(value = "{id}")
    public JsonResult getUserById(@PathVariable(value = "id") int id){
        log.debug("id:"+id);
    User user= userMapper.selectUserById(id);
        return JsonResult.ok(user);
    }
}